title | description | canonical | status | lastmod |
---|---|---|---|---|
The Index attribute in Entity Framework Core |
The Entity Framework Core `IndexAttribute` was introduced in .NET 5 and is used to create a database index on the column mapped to the specified entity property. |
/configuration/data-annotation-attributes/index-attribute |
Published |
2023-02-28 |
The Entity Framework Core IndexAttribute
was introduced in .NET 5 and is used to create a database index on the column mapped to the specified entity property. By default, indexes are created for foreign keys and alternate keys. You may wish to create indexes on other properties to speed up data retrieval. The following example sets a non-unique index on the Isbn
column:
[Index(nameof(Isbn))]
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string Isbn { get; set; }
}
To create a unique index, you must specify IsUnique=true
:
[Index(nameof(Isbn), IsUnique=true)]
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string Isbn { get; set; }
}
If you wish to apply an index on more than one column, you specify them as a comma separate value.
[Index(nameof(Ssn),nameof(DateOfBirth))]
public class Patient
{
public int PatientId { get; set; }
public string Ssn { get; set; }
public DateTime DateOfBirth { get; set; }
}
The name of the generated index follows the patter IX__ by default. You can alter this using the Name property of the Index attribute:
[Index(nameof(Isbn), IsUnique=true, Name="Unique_Isbn")]
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string Isbn { get; set; }
}
The Fluent API equivalent method for the Index
attribute is the HasIndex method